package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {


    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    /**
     * 获取全部的课程分页--树型结构
     * @return
     */
    @Override
    public List<CourseCategoryTreeDto> createListCourseCategoryTree(String id) {
        //递归先拿到课程分类所有的分类信息
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        //找到每个节点的子节点，最终封装成List<CourseCategoryTreeDto>
        //先将List转换成map，key就是节点的id，value就是CourseCategoryTreeDto对象，目的就是方便从map中后去节点,也要过滤掉根节点
        Map<String, CourseCategoryTreeDto> treeDtoMap = courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        //定义一个List作为最终返回list
        List<CourseCategoryTreeDto> categoryTreeDtoList = new ArrayList<>();
        //从头开始遍历List<CourseCategoryTreeDto>，一边遍历一边找子节点放在父节点的childrentreeNodes中
        courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).forEach(item->{
            //判断父节点是否等于id
            if (item.getParentid().equals(id)){
                categoryTreeDtoList.add(item);
            }
            //找到每个子节点，放在父节点的childrentreeNodes属性中
            CourseCategoryTreeDto treeDto = treeDtoMap.get(item.getParentid());
            if (treeDto!=null){
                if (treeDto.getChildrenTreeNodes()==null){
                    //如果该父节点ChildrenTreeNodes为空，需要为其new一个集合，因为该集合需要放它的子节点
                    treeDto.setChildrenTreeNodes(new ArrayList<>());
                }
                //把每一个节点的子节点放在父节点的childrentreeNodes属性中
                treeDto.getChildrenTreeNodes().add(item);
            }
        });


        return categoryTreeDtoList;
    }
}
